package spring.boot.admin.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import spring.boot.admin.handler.AuthLimitHandler;
import spring.boot.admin.handler.LoginFailHandler;
import spring.boot.admin.handler.LoginSuccessHandler;
import spring.boot.admin.model.SysUser;
import spring.boot.admin.service.SysUserService;

/**
 * @author guoyibin
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SysUserService sysUserService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 关闭csrf
        http.csrf().disable();
        http.headers().frameOptions().disable();
        // 配置登录页面
        http.formLogin().loginPage("/login").permitAll();
        // 配置登录成功后的操作
        http.formLogin().successHandler(new LoginSuccessHandler());
        http.formLogin().failureHandler(new LoginFailHandler());
        // 用户权限不足处理器
        http.exceptionHandling().accessDeniedHandler(new AuthLimitHandler());
        // 登出授权
        http.logout().permitAll();
        // 授权配置
        http.authorizeRequests()
                .antMatchers("/topjui/**", "/bootstrap/**", "/font-awesome/**").permitAll()
                .antMatchers("/images/**", "/jquery/**", "/easyui/**").permitAll()
                .antMatchers("/login/**").permitAll()
                .anyRequest().authenticated();
    }

    @Override
    protected UserDetailsService userDetailsService() {
        return username -> {
            if (username == null || username.trim().length() <= 0) {
                throw new UsernameNotFoundException("用户名为空");
            }
            //查询用户的信息以及所有的角色和权限
            SysUser sysUser = sysUserService.selectByUserName(username);
            if (sysUser != null) {
                return sysUser;
            }
            throw new UsernameNotFoundException("用户不存在!");
        };
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
    }

}

